<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <body>
        <div>
            用户名：<input type="text" id="username" value=""><br />
            密码：&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" id="password"><br />
            <input type="checkbox" id="rember" check="true">记住密码
           <a href="index.html"><button type="submit" id="dl">登陆</button></a> 
        </div>
        <script>
        window.onload = function(){
            var name = document.getElementById("username");
            var pswd = document.getElementById("password");
            var dl = document.getElementById("dl");
            var orember = document.getElementById("rember");
    //		var cuser = document.cookie = "user"+"="+name.value+";";
    //		var cpswd = document.cookie = "password"+"="+pswd.value+";";
            //页面初始化时，如果帐号密码cookie存在则填充
            if(getCookie('username')&& getCookie('password')){
                name.value = getCookie('username');
                pswd.value = getCookie('password');
                orember.checked = true;
            }
            //复选框勾选状态发生改变时，如果未勾选则清除cookie
            orember.onchange = function(){
                if(!this.checked){
                    delCookie('username');
                    delCookie('password');
                }
                else{
                    this.style.display = "block";
                }
            }
            //表单提交事件触发时，如果复选框是勾选状态则保存cookie
            dl.onsubmit =function(){
                if(remember.checked){ 
                    setCookie('username',name.value,7); //保存帐号到cookie，有效期7天
                    setCookie('password',pswd.value,7); //保存密码到cookie，有效期7天
                  }
              
            }
        };
            
        //设置cookie
            function setCookie(name,value,day){
                var date = new Date();
                date.setDate(date.getDate() + day);
                document.cookie = name + '=' + value + ';expires='+ date;
             };
            
        //获取cookie
            function getCookie(name){
                var reg = RegExp(name+'=([^;]+)');
                var arr = document.cookie.match(reg);
                if(arr){
                  return arr[1];
                }else{
                  return '';
                }
             };
            
        //删除cookie
            function delCookie(name){
                setCookie(name,null,-1);
             }
        </script>
    </body>
    
</body>
</html>